#include "net/net.h" 
#include "pack/pack.h" 

#include <signal.h>

#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;

class HelloWorldPacket : public pack::IPacket {
	public:
		std::string str;	

	public:
		HelloWorldPacket() {

		}

		~HelloWorldPacket() {
            cout<<"~HelloWorldPacket"<<endl;
		}

		uint32_t GetUri() {
			return 1;
		}

		bool Pack(pack::Writer& writer) {
			writer<<str;
			return true;
		}

		bool UnPack(pack::Reader& reader) {
			return reader>>str;
		}

        std::string Dump() {

        }
};

class SocketHandler : public net::ISocketHandler {
	public:
		virtual void OnRead(net::ISocket* socket) {
			HelloWorldPacket packet;
			pack::Request in_request(socket->GetInBuffer());
			pack::Request out_request(socket->GetOutBuffer());

			while(in_request.GetPack()) {
				if(in_request.UnPack(&packet)) {
					cout<<packet.str<<endl;
				}
			}

			int n = rand() % 100;

			packet.str = "";
			for(int i = 0; i < n; i++) {
				packet.str += "Server";
			}
			out_request.Pack(&packet);
			socket->Send("", 0);
            cout<<"OnRead-----"<<endl;
		}

		virtual void OnWrite(net::ISocket* socket) {

		}

		virtual void OnClose(net::ISocket* socket) {
            delete this;
		}

		virtual void OnConnected(net::ISocket* socket) {

		}

		virtual void OnError(net::ISocket* socket, uint32_t error) {

		}
};

class AcceptHandler : public net::IAccepterHandler {
	public:
		virtual void OnAccept(net::ISocket* socket) {
			socket->SetHandler(new SocketHandler);
		}
};

void Init() {
	struct sigaction sa;

	sa.sa_handler = SIG_IGN;
	sa.sa_flags = 0;
	if(sigemptyset(&sa.sa_mask) == -1 || sigaction(SIGPIPE, &sa, 0) == -1) {
		cout<<"忽略PIPE信号发生错误"<<endl;
		exit(1);
	}
}

int main() {
	AcceptHandler handler;
	net::NetAddress address("127.0.0.1", 9999);
	net::IReactor* reactor = net::GetReactor();
	net::IAccepter* accepter = net::GetAccepter();

	Init();

	accepter->Listen(address);
	accepter->SetHandler(&handler);

	reactor->Dispatch();
	return 0;
}
